import React, { useState, useEffect, useRef,useContext } from 'react'
import { ThemeContext } from '../App'
import useMousePosition from '../hooks/useMousePosition'


const LikeButton: React.FC = () => {
    const [like, setLike] = useState(0)
    const [on, setOn] = useState(true)
    const positions = useMousePosition()
    const likeRef = useRef(0)
    const didMountRef = useRef(false)
    const domRef = useRef<HTMLInputElement>(null)
    const theme = useContext(ThemeContext);
    
    const style = {
        color: theme.color,
        background: theme.background
    }
    useEffect(() => {
        console.log("document title effect is running")
        document.title = `点击率${like}次`
    }, [like])
useEffect(() => {
   if (domRef && domRef.current) {
       domRef.current.focus()
   }
})

    function handleAlert() {
        setTimeout(() => {
            alert('you click on ' + likeRef.current)
        }, 3000);
    }
    useEffect(() => {
        if (didMountRef.current) {
         console.log("this is update")   
        } else {
            didMountRef.current = true
        }
    })

    return <div>
        <input type="text" ref={domRef} ></input>
        <p>X :{positions.x}, Y : {positions.y}</p>
        <button style={style} onClick={() => {
            setLike(like + 1);
            likeRef.current++;
        }}>
            {like} 👍🏻
        </button>
        <button onClick={handleAlert}>
            {on ? "ON" : "OFF"}
        </button>
    </div>

    // const [obj, setObj] = useState({ like: 0, on: true })
    // return <div>
    //     <button onClick={() => { setObj({ like: obj.like + 1, on: obj.on }) }}>
    //         {obj.like} 👍🏻
    //     </button>
    //     <button onClick={() => { setObj({ like: obj.like, on: !obj.on }) }}>
    //         {obj.on? "ON":"OFF"} 
    //     </button>
    // </div>
}

export default LikeButton